package com.heima.comment.service.impl;

import com.alibaba.nacos.api.config.filter.IFilterConfig;
import com.heima.aliyun.GreenTextScan;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustomException;
import com.heima.feigns.uesr.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vo.ApCommentRepayVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;


import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    GreenTextScan greenTextScan;

    //展示评论回复信息列表
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        //检查参数
        if (dto == null || dto.getCommentId() == null || dto.getMinDate() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getSize() == null || dto.getSize() <= 0) {
            dto.setSize(10);
        }
        //按照文章id过滤，设置分页和排序
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId())
                .and("createdTime").lt(dto.getMinDate()));
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query, ApCommentRepay.class);
        //数据封装返回
        //用户未登录 加载数据
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.okResult(apCommentRepays);
        }
        List<String> idList = apCommentRepays.stream().map(x -> x.getId()).collect(Collectors.toList());
        Query query1 = Query.query(Criteria.where("commentRepayId").in(idList).and("authorId").is(user.getId()));
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(query1, ApCommentRepayLike.class);
        //创建ApCommentRepayVo返回对象
        List<ApCommentRepayVo> resultList = new ArrayList<>();
        if (apCommentRepays != null && apCommentRepayLikes != null) {
            apCommentRepays.stream().forEach(x -> {
                ApCommentRepayVo apCommentRepayVo = new ApCommentRepayVo();
                BeanUtils.copyProperties(x, apCommentRepayVo);
                for (ApCommentRepayLike apCommentRepayLike : apCommentRepayLikes) {
                    if (x.getId().equals(apCommentRepayLike.getCommentRepayId())) {
                        apCommentRepayVo.setOperation((short) 0);
                    }
                }
                resultList.add(apCommentRepayVo);
            });
            return ResponseResult.okResult(resultList);
        }
        return ResponseResult.okResult(apCommentRepays);
    }

    //保存评论回复信息
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        //检查参数
        if (dto == null || dto.getCommentId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getContent() == null || dto.getContent().length() > 140) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID, "不可空评论或超出长度");
        }
        //判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //查询用户
        ApUser apUser = userFeign.findUserById(user.getId().longValue());
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户信息不存在");
        }
        //安全过滤,
        try {
            Map map = greenTextScan.greenTextScan(dto.getContent());
            String suggestion = (String) map.get("suggestion");
            //4.保存评论
            if ("pass".equals(suggestion)) {
                ApCommentRepay apCommentRepay = new ApCommentRepay();
                apCommentRepay.setAuthorId(apUser.getId());
                apCommentRepay.setAuthorName(apUser.getName());
                apCommentRepay.setContent(dto.getContent());
                apCommentRepay.setCommentId(dto.getCommentId());
                apCommentRepay.setCreatedTime(new Date());
                apCommentRepay.setUpdatedTime(new Date());
                apCommentRepay.setLikes(0);
                mongoTemplate.insert(apCommentRepay);
                //更新评论的回复数量
                ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
                apComment.setReply(apComment.getReply() + 1);
                mongoTemplate.save(apComment);
                return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回数据
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "存在敏感词，请重新评论");
    }

    //保存评论回复信息点赞
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDto dto) {
        //检查参数
        if (dto == null || dto.getCommentRepayId() == null || (dto.getOperation() < 0 && dto.getOperation() > 1)) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //点赞操作
        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if (apCommentRepay == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "该评论已经被删除");
        }
        if (apCommentRepay != null) {
            ApCommentRepayLike apCommentRepayLike = mongoTemplate.findById(apCommentRepay.getId(), ApCommentRepayLike.class);
            if (apCommentRepayLike != null && apCommentRepayLike.getOperation() == 0) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "无需重复点赞");
            }
        }
        if (apCommentRepay != null && dto.getOperation() == 0) {
            //更新评论的点赞数量
            apCommentRepay.setLikes(apCommentRepay.getLikes() + 1);
            mongoTemplate.save(apCommentRepay);
            //保存 APP评论信息点赞
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(user.getId());
            apCommentRepayLike.setCommentRepayId(apCommentRepay.getId());
            apCommentRepayLike.setOperation((short) 0);
            mongoTemplate.insert(apCommentRepayLike);
        } else {
            //取消点赞
            //更新评论的点赞数量
            apCommentRepay.setLikes(apCommentRepay.getLikes() <= 0 ? 0 : apCommentRepay.getLikes() - 1);
            //更新APP评论信息点赞表
             mongoTemplate.remove(Query.query(Criteria.where("authorId")
                     .is(user.getId()).and("commentRepayId")
                     .is(apCommentRepay.getId())), ApCommentRepayLike.class);
        }
        //5.数据返回
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("likes",apCommentRepay.getLikes());
        return ResponseResult.okResult(resultMap);
    }
}
